package com.sj.security;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.sj.common.lang.ApiResultMsg;
import com.sj.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-08-02
 * Time: 下午 19:11
 * Description: 退出处理器
 * @author xiaoqi
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(httpServletRequest, response, authentication);
        }

        response.setHeader(jwtUtils.getHeader(), "");
        // 生成jwt
        ApiResultMsg resultMsg = ApiResultMsg.success("退出成功");
        outputStream.write(JSONUtil.toJsonStr(resultMsg).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}